package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.NearUserVo;
import com.tanhua.domain.vo.UserLocationVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mg.UserLocationApi;
import com.tanhua.server.utils.ThreadLocalUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class UserLocationService {
    //订阅UserLocationApi
    @Reference
    private UserLocationApi userLocationApi;
    //订阅UserInfoApi
    @Reference
    private UserInfoApi userInfoApi;
    //注入ThreadLocalUtils
    @Autowired
    private ThreadLocalUtils threadLocalUtils;


    /**
     * 上报地理信息
     */
    public void saveLocation(Map map) {
        //获取当前的用户id
        Long currentUserId = threadLocalUtils.getUserId();
        //根据当前用户id查询性别
        UserInfo userInfo = userInfoApi.findUserInfoByID(currentUserId);
        String gender = userInfo.getGender();
        //分别获取map集合中的经纬度和位置
        Double latitude = (Double) map.get("latitude");
        Double longitude = (Double) map.get("longitude");
        String addrStr = (String) map.get("addrStr");
        //传入参数
        userLocationApi.saveLocation(latitude,longitude,addrStr,currentUserId,gender);

    }
    /**
     * 搜附近
     */
    public List<NearUserVo> searchNearby(String gender, Long distance) {
        //获取当前用户id
        Long currentUserId = threadLocalUtils.getUserId();
        //c.调用api服务接口 传入gender,distance,currentUserId 返回List<userLocationvo>
        List<UserLocationVo> locationVos= userLocationApi.searchNearby(currentUserId,distance,gender);
        ArrayList<NearUserVo> nearUserVoArrayList = new ArrayList<>();
        //d.判断非空 遍历list集合
        if (CollectionUtils.isNotEmpty(locationVos)){
            for (UserLocationVo locationVo : locationVos) {
                NearUserVo nearUserVo = new NearUserVo();
                //e.得到集合中的userId
                Long voUserId = locationVo.getUserId();
                //f.根据用户id查询userInfo信息
                UserInfo userInfo = userInfoApi.findUserInfoByID(voUserId);
                //判断查询的的用户是否是当前的用户
                if(userInfo.getId().equals(currentUserId)){
                    continue;//跳过本次循环 进入下次循环
                }
                //g.封装数据
                BeanUtils.copyProperties(userInfo,nearUserVo);
                nearUserVoArrayList.add(nearUserVo);
            }
            return nearUserVoArrayList;
        }
       return null;//没搜索到附近的用户
    }
}
